import java.sql.Timestamp

import de.fhk.fst.dvr.association.UserGroupAssociation
import de.fhk.fst.dvr.info.TVStation
import de.fhk.fst.dvr.recording.TvShow
import de.fhk.fst.dvr.user.User
import de.fhk.fst.dvr.user.UserGroup

class BootStrap {

  def init = { servletContext ->
    Calendar cal = Calendar.getInstance()
    cal.set Calendar.YEAR,2000
    cal.set Calendar.MONTH,Calendar.JANUARY
    cal.set Calendar.DAY_OF_MONTH,15
    initUserGroups()
    initUsers(cal)
    initTvStations()
    initTvShows(cal)
  }

  def destroy = {
  }

  void initUserGroups() {
    def adminGroup = new UserGroup(groupName: "Admin", adminGroup: true)
    adminGroup.save(flush: true)
    def userGroup = new UserGroup(groupName: "Users", adminGroup: false)
    userGroup.save(flush: true)
  }

  void initUsers( Calendar cal ) {
    def testUser = new User(username: "testadmin", firstname: "test", lastname: "test", email: "test@test.de", password: "test123", dateOfBirth: new Date(cal.getTimeInMillis()) )
    testUser.save(flush:true)
    def userAssociationRoot = new UserGroupAssociation(user: User.findByUsername("testadmin"), group: UserGroup.findByGroupName("Admin"))
    userAssociationRoot.save(flush:true)
    testUser = new User(username: "testuser", firstname: "test", lastname: "test", email: "test@testuser.de", password: "test123", dateOfBirth: new Date(cal.getTimeInMillis()) )
    testUser.save(flush:true)
  }

  void initTvStations() {
    TVStation station = new TVStation(name: "RTL")
    station.save()

    station = new TVStation(name: "PRO7")
    station.save()
  }

  void initTvShows(Calendar cal) {
    cal.set Calendar.YEAR, Calendar.getInstance().get(Calendar.YEAR)
    cal.set Calendar.MONTH, Calendar.getInstance().get(Calendar.MONTH)
    cal.set Calendar.DAY_OF_MONTH, Calendar.getInstance().get(Calendar.DAY_OF_MONTH)
    cal.set Calendar.HOUR, 20
    cal.set Calendar.MINUTE, 15
    def start = new Timestamp(cal.getTimeInMillis())
    cal.set Calendar.HOUR, 22
    def end = new Timestamp(cal.getTimeInMillis())
    TvShow show = new TvShow(name: "DSDS", station: TVStation.findByName("RTL"), startTime: start, endTime: end )
    show.save()
  }
}
